import { Component, OnInit, ViewChild } from '@angular/core';
import { Service } from '../../server/server';
import { HeaderService } from '../services/header.service';
import { Router,ActivatedRoute, Params } from '@angular/router';
import { HttpClientModule, HttpClient, HttpErrorResponse } from '@angular/common/http';
import { MessageComponent } from './message/message.component';
import { LocalStorageService } from '../../public/serve/local-storage/local-storage.service';
declare var $: any;

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
})
export class HeaderComponent implements OnInit {

  public right: any = {
    "home": {},
    "user": {},
    "system": {},
    "goods": {},
    "order": {},
    "gateway": {},
    "root_roles": {},
    "root_user": {},
    "root_privilege": {},
    "root_openPlatform": {},
    "root_system": {},
    "root_storage": {},
    "root_resource": {},
    "root_product": {},
    "root_order": {},
    "root_gateway": {},
    "root_pavmenu": {},
    //用户
    "roles": {},
    "role": {},
    "personal": {},
    "institution": {},
    "privilege": {},
    "effect": {},
    //系统
    "sysconfig": {},
    "register": {},
    "task": {},
    "journal": {},
    "sso": {},
    "database": {},
    "terminal": {},
    "ip-rule": {},
    "scope-authorization": {},
    "application": {},

    //内容
    "content": {},
    "content_product": {},
    "innertext": {},

    //报表管理
    "report":{},
    "reportInner":{},
    "reportProduct":{},
    "reportCase":{},
    "reportTheme":{},
    "reportUseby":{},

    //同义词管理
    "synonym": {},

    //主题词管理
    "keyword": {},
    "root_keyword": {},
    "keywordTrial": {},
    "keywordUnreviewed": {},
    "systemTable": {},
    "systemThemeTag": {},
    "systemTableTag": {},

    //系统设置
    "systemPushed": {},
    "systemTemplateTath": {},
    "systemProductType": {},
    "systemInnerindexStyle": {},
    "systemDatabase": {},

    //内容管理
    "contentInnertext": {},
    "contentProduct": {},

    //标引任务管理 Start
    "indexingTask": {},
    //产品标引任务
    "product": {},
    "productAudit": {},
    "productList": {},
    "productTaskContent": {},
    "productIndexingTask": {},
    //内文标引任务
    "internal":{},
    "internalAudit": {},
    "internalList": {},
    "internalTaskContent": {},
    "internalIndexingTask": {},
    //主题词标引任务
    "themeInternal":{},
    "themeTaskAudit": {},
    "themeTaskList": {},
    "themeTaskContent": {},
    "themeContentIndexing": {},
    //模板管理
    "template":{},
    "templateAttribute": {},
    //项目管理
    "systemProject": {},

    //标引任务管理 End

  };
  //登录用户ID
  public createUserId: any;
  //登录用户昵称
  public userName: string;
  //登录用户名
  public realName: string;
  //头像
  public portrait: any;
  //门户
  public websites: any;

  //有无权限
  public isjurisdiction: number = 0;
  constructor(
    public server: Service, 
    public router: Router, 
    private http: HttpClient,
    private headerService: HeaderService, 
    private localStorageService: LocalStorageService,
    private activatedRoute:ActivatedRoute
  ) {
    this.right = $.extend(this.right, server.getRight());
    //判断目录下是否配置权限
    //首页
    if (!this.right['home']['addUser'] && !this.right['home']['addJg'] && !this.right['home']['addFg'] && !this.right['home']['publishOrder']) {
      this.right.home = {};
      this.isjurisdiction++;
    }
    //用户管理
    if (!this.right['root_roles']['view'] && !this.right['root_user']['view'] && !this.right['root_privilege']['view']) {
      this.right.user = {};
      this.isjurisdiction++;
    }
    //系统管理
    if (!this.right['sysconfig']['view'] && !this.right['systemProductType']['view'] && !this.right['systemInnerindexStyle']['view'] && !this.right['systemDatabase']['view']) {
      this.right.system = {};
      this.isjurisdiction++;
    }
    //主题词管理
    if (!this.right['root_keyword']['view'] && !this.right['systemThemeTag']['view'] && !this.right['systemTable']['view'] && !this.right['systemTableTag']['view']) {
      this.right.keyword = {};
      this.isjurisdiction++;
    }
    //报表管理
    if (!this.right['reportInner']['view'] && !this.right['reportProduct']['view'] && !this.right['reportCase']['view'] && !this.right['reportTheme']['view'] && !this.right['reportUseby']['view']) {
      this.right.report = {};
      this.isjurisdiction++;
    }
    //内容管理
    if (!this.right['contentInnertext']['view'] && !this.right['contentProduct']['view']) {
      this.right.content = {};
      this.isjurisdiction++;

    }
    //标引任务管理
    if (!this.right['internal']['view'] && !this.right['product']['view'] && !this.right['themeInternal']['view'] && !this.right['template']['view'] && !this.right['templateAttribute']['view'] && !this.right['systemProject']['view']) {
      this.right.indexingTask = {};
      this.isjurisdiction++;

    }

    //无任何权限
    // if (this.isjurisdiction == 6) {
    //   this.router.navigate(['jurisdiction']);
    // }
    this.createUserId = this.server.getuser();
    this.userName = this.server.getuserName();
    // this.portrait = this.server.getuserPortrait();
    // this.websites = this.server.getwebsites();
    this.realName = this.server.getRealName();
  }

  public isActive = this.server.isActive;
  public taskType:any;
  ngOnInit() {
    this.tabBoxData = [];
    this.activatedRoute.queryParams.subscribe((p: Params) => {
      this.taskType = String(p['taskType']);
      if( this.taskType == '0' || this.taskType == '1' || this.taskType == '2'){
        this._tabRouterUrl();
      }
    });
    this.activatedRoute.url.subscribe(res => {
      if( !this.router.url.includes('/product/list')){
        this._tabRouterUrl();
      }
    })
    this.server.eventEmit.subscribe((value: any) => {
      this.isActive = value;
    });
    //接受logo
    this.websiteseventEmit = this.server.websiteseventEmit.subscribe((value: any) => {
      if (value) {
        this.websites = this.server.getwebsites();
      }
    });
    //接收昵称
    this.usernameeventEmit = this.server.usernameeventEmit.subscribe((value: any) => {
      if (value) {
        this.userName = this.server.getuserName();
      }
    });
    //接收头像
    this.userportraiteventEmit = this.server.userportraiteventEmit.subscribe((value: any) => {
      if (value) {
        this.portrait = this.server.getuserPortrait();
      }
    });
    //接收权限
    this.righteventEmit = this.server.righteventEmit.subscribe((value: any) => {
      if (value) {
        this.right = $.extend(this.right, this.server.getRight());
      }
    });
    ///console.log(this.createUserId)
    if (this.createUserId == null) {
      this.router.navigateByUrl('login');
    }
    this.refresheventEmit = this.server.refresheventEmit.subscribe((value: any) => {
      this.right = value
    });

    if (this.router.url.indexOf('/product/resourceclassify/') >= 0) {
      this.productActive = true;
    }
    if (this.router.url.indexOf('/user') >= 0) {
      this.userActive = true;
    }
    if (this.router.url.indexOf('/gateway') >= 0) {
      this.gatewayActive = true;
    }
    if (this.router.url.indexOf('/order/person') >= 0) {
      this.orderActive = true;
    }
    //资源active
    this.resourceclassifyeventEmit = this.server.resourceclassifyeventEmit.subscribe((value: any) => {
      if (value) {
        this.productActive = true;
      }
    });
    //推送消息
    // this.cancelWebSocketEimt = this.websocketService.webSocketName.subscribe((value: any) => {
    //   //console.log(value)
    //   try {
    //     value = (new Function("return " + value))()
    //     if (this.createUserId == value.ReceiveUserId) {
    //       this.counts = value.ReceiveUserIdNoReadCount;
    //       if (this.counts > 0) {
    //         this.websocketService.openModel.emit(this.counts)
    //       }
    //     }
    //   } catch (error) {

    //   }
    // });

    //订单计数
    this.cancelMessageOrderEimt = this.server.messageOrder.subscribe((value: any) => {
      this.countsOrder = value;
    })
    //入库计数
    this.cancelMessageStorageEimt = this.server.messageStorage.subscribe((value: any) => {
      this.countsStorage = value;
    })

    //入库合同
    this.cancelMessageContractEimt = this.server.messageContract.subscribe((value: any) => {
      this.countsContract = value;
    })

    //关闭当前页面
    this.closeCurrentPageEimt = this.server.closeCurrentPageEimt.subscribe((val: any) => {
      if(val){
        this.closeTabBox(val,'');
      }
      
    })

  }

  //取消订阅
  public cancelWebSocketEimt: any;
  public cancelMessageOrderEimt: any;
  public cancelMessageStorageEimt: any;
  public cancelMessageContractEimt:any;
  public websiteseventEmit: any;
  public usernameeventEmit: any;
  public userportraiteventEmit: any;
  public righteventEmit: any;
  public refresheventEmit: any;
  public resourceclassifyeventEmit: any;
  public closeCurrentPageEimt:any;
  ngOnDestroy() {
    if (
      this.cancelWebSocketEimt ||
      this.cancelMessageOrderEimt ||
      this.cancelMessageStorageEimt ||
      this.websiteseventEmit ||
      this.usernameeventEmit ||
      this.userportraiteventEmit ||
      this.righteventEmit ||
      this.refresheventEmit ||
      this.resourceclassifyeventEmit ||
      this.cancelMessageContractEimt ||
      this.closeCurrentPageEimt
    ) {
      //this.cancelWebSocketEimt.unsubscribe();
      this.cancelMessageOrderEimt.unsubscribe();
      this.cancelMessageStorageEimt.unsubscribe();
      this.websiteseventEmit.unsubscribe();
      this.usernameeventEmit.unsubscribe();
      this.userportraiteventEmit.unsubscribe();
      this.righteventEmit.unsubscribe();
      this.refresheventEmit.unsubscribe();
      this.resourceclassifyeventEmit.unsubscribe();
      this.cancelMessageContractEimt.unsubscribe();
      this.closeCurrentPageEimt.unsubscribe();
    }
  }

  public countsOrder: any = 0;
  public countsStorage: any = 0;
  public countsContract:any = 0;

  @ViewChild("message") message: MessageComponent;
  //计数
  public counts: number = 0;
  public websocketData: any;
  ngDoCheck() {
    this.right = $.extend(this.right, this.server.getRight());
    //ipad导航
    // $(".fork").click(function(){
    //   $(this).parent("li.animate-time").addClass("active").siblings().removeClass("active");
    // })
    if (document.body.offsetWidth < 1020) {
      $(".navbar-nav>li").click(function () {
        $(this).addClass("active").siblings().removeClass("active");
      })

      $(".ipad-header-ul li").click(() => {
        $(".navbar-toggle").removeClass("active");
        $(".navbar-collapse").removeClass("in");
        this.switchmodel = false;
      })
    }
    this.counts = Number(this.countsOrder) + Number(this.countsStorage) + Number(this.countsContract);
    if(!this.router.url.includes("/order")){
      this.server.headTitle = "合同订单";
    }
  }
  //导航按钮
  public switchmodel: boolean = false;
  public switch() {
    this.switchmodel = !this.switchmodel;
  }
  // public copyswitch(){
  //   if(document.body.offsetWidth < 1020){
  //    $(".navbar-toggle").click();
  //   }
  // }
  //开关阴影
  // public ocshadow(){
  //   if(document.body.offsetWidth < 1020){
  //     this.server.closeindentbutton();
  //   }  
  // }

  //product active
  public productActive: any;
  public orderActive: any;
  public userActive: any;
  public gatewayActive: any;

  //home导航点击
  public homeclick() {

  }

  _tabRouterUrl(){
    let tabSession = JSON.parse(sessionStorage.getItem('tabData')) || [{name: "首页", value: "/home"}];
      this.tabBoxDatatest = [];
      this.tabBoxData = tabSession;
      for(let t of this.tabBoxData){
          this.tabBoxDatatest.push(t.value);
      }
      if(this.tabBoxDatatest.indexOf(this.router.url) == -1){
        for(let v of this.headerService.tabData){
          if(v.value && this.router.url.indexOf(v.value) >= 0){
            let name = v.name;
            if(this.router.url.indexOf('taskType=1') >= 0){
              name = '内文'+v.name;
            }else if(this.router.url.indexOf('taskType=0') >= 0){
              name = '产品'+v.name;
            }else if(this.router.url.indexOf('taskType=2') >= 0){
              name = '主题词'+v.name;
            }else if(this.router.url.indexOf('roles') >= 0){
              name = '角色组管理';
            }
            this.tabBoxDataOne = {'name' : name , 'value':  encodeURI(this.router.url)};
          }
          if(v.value == this.router.url){
            this.tabBoxDataOne = v;
          };
        }
        if(this.tabBoxDatatest.length == 10){
          this.tabBoxData.splice(0,1);
        }
        this.tabBoxData.push(this.tabBoxDataOne);
        sessionStorage.setItem('tabData',JSON.stringify(this.tabBoxData));
      }
  }

  //产品标引任务导航点击
  public indexingtasklist() {
    if (document.body.offsetWidth > 1020) {
      this.headerService.indexingtasklist();
    } else {
      // this.router.navigateByUrl('/product/resourcetype');
    }
  }

  //产品标引任务导航点击
  public productclick() {
    if (document.body.offsetWidth > 1020) {
      this.headerService.productclick();
    } else {
      // this.router.navigateByUrl('/product/resourcetype');
    }
  }

  //内文标引任务导航点击
  public internalclick() {
    if (document.body.offsetWidth > 1020) {
      this.headerService.internalclick();
    } else {
      // this.router.navigateByUrl('/product/resourcetype');
    }
  }

  //主题词标引任务导航点击
  public themeInternalclick(){
    if (document.body.offsetWidth > 1020) {
      this.headerService.themeInternalclick();
    } else {
      // this.router.navigateByUrl('/product/resourcetype');
    }
  }

  //主题词管理导航点击
  public keywordclick() {
    if (document.body.offsetWidth > 1020) {
      this.headerService.keywordclick();
    } else {
      // this.router.navigateByUrl('/product/resourcetype');
    }
  }
  //同义词管理导航点击
  public synonymclick() {
    if (document.body.offsetWidth > 1020) {
      this.headerService.synonymclick();
    } else {
      // this.router.navigateByUrl('/product/resourcetype');
    }
  }

  //内容管理导航点击
  public contentclick() {
    if (document.body.offsetWidth > 1020) {
      this.headerService.contentclick();
    } else {
      // this.router.navigateByUrl('/product/resourcetype');
    }
  }

   //报表管理导航点击
   public reportclick() {
    if (document.body.offsetWidth > 1020) {
      this.headerService.reportclick();
    } else {
      // this.router.navigateByUrl('/product/resourcetype');
    }
  }

  //用户导航点击
  public userclick() {
    if (document.body.offsetWidth > 1020) {
      this.headerService.userclick();
    } else {
      //this.router.navigateByUrl('/user/roles');
    }
  }

  //系统导航点击
  public systemclick() {
    if (document.body.offsetWidth > 1020) {
      this.headerService.systemclick();
    } else {
      //this.router.navigateByUrl('/system/sysconfig');
    }
  }

  //登出
  public logout(realName) {
    this.closeAll();
    let url = this.server.baseUrl+'admin/pusers/logout';
    let data = {
      userName: realName
    }
    this.http.post<Response>(url, data).subscribe((res: any) => {
      var backUrl = res.back_url.toString();
      if (undefined != backUrl && backUrl == 'login') {
        sessionStorage.removeItem("user-rights");
        sessionStorage.removeItem("user");
        sessionStorage.removeItem("username");
        sessionStorage.removeItem("realName");
        this.headerService.load();
        this.router.navigateByUrl(backUrl);
      }
    })
  }
  //
  public isOrderUrlActive() {
    return /\/order/.test(this.router.url)
  }

  //消息点击
  public horn() {
    //this.websocketService.hornClick.emit();
  }

  //count
  // public messageCount(val){
  //   this.counts = val;
  // }

  public contractTo(){
    this.server.contracteventEmit.emit();
  }

  public personTo(){
    this.server.ordereventEmit.emit();
  }

  public tabBoxData:Array<any>;//总数据
  public tabBoxDataOne:any; //单条数据
  public tabBoxDatatest:any; //临时数据
  //关闭历史记录
  public closeTabBox(val,e){
    if((this.tabBoxData.length != 1 && this.tabBoxData[0]['value'] == '/home') || (this.tabBoxData.length > 1)){

      let sess = JSON.parse(sessionStorage.getItem('tabData'));
      if(sess.length != 1 && val != '/home'){
        let endUtl = '';
        sess.forEach(( item, i ) =>{
          if(item.value == val){
            sess.splice(i,1);
          }else{
            endUtl = item.value;
          }
        })
        this.tabBoxData = sess;
        sessionStorage.setItem('tabData',JSON.stringify(sess));
        if(e){
          e.stopPropagation();
        }
        
        this.router.navigateByUrl(endUtl);
      }
    }
    
  }

  closeAll(){
    if((this.tabBoxData.length != 1 && this.tabBoxData[0]['value'] == '/home') || (this.tabBoxData.length > 1)){
      sessionStorage.removeItem('tabData');
      this.tabBoxData = [{name: "首页", value: "/home"}];
      this.router.navigateByUrl('/home');
    }
  }

  tiv(){
    if(!this.router.url.includes('content')){
      this.router.navigate(['/content/product'] ); 
    }
  }

  clo(){
    $('#contentExample').collapse('hide');
  }
}
